<?php

namespace app\api\controller;

use think\facade\Validate;
use think\facade\Db;
use app\lib\Result;

class Schedule extends Base
{
  public function editCateItem()
  {
    if (request()->isPost()) {
      $rule = [
        'title|分类名' => 'require|max:32',
      ];
      $data = [
        '_id' => input('param._id', '', 'trim'),
        'title' => input('param.title', '', 'trim'),
        'is_default' => input('param.is_default', 0, 'trim'),
        'desc' => input('param.desc', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result = $validate->check($data);
      if (!$result) {
        return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
      }
      $data['is_default'] = intval($data['is_default']);
      if ($data['is_default']==1) {
        Db::connect('mongodb')->name('schedule_cate')->update(['is_default' => 0]);
      }
      if (!empty($data['_id'])) {
        $status = Db::connect('mongodb')->name('schedule_cate')->where('_id', $data['_id'])->update($data);
        $tag = '编辑';
      } else {
        $data['create_time'] = time();
        $data['_id'] = createId();
        
        $status = Db::connect('mongodb')->name('schedule_cate')->insert($data);
        $tag = '新增';
      }
      if ($status > 0) {
        return json(['code' => 200, 'data' => '', 'msg' => $tag . '成功']);
      } else {
        return json(['code' => -1, 'data' => '', 'msg' => $tag . '失败，请重试']);
      }
    } else {
      $id = input('param.id', '', 'trim');
      if (!$id) {
        return json(['code' => 200, 'data' => [], 'msg' => 'success']);
      }
      $data = Db::connect('mongodb')->name('schedule_cate')->where('_id', $id)->find();
      return json(['code' => 200, 'data' => $data, 'msg' => 'success']);
    }
  }
  public function editScheduleInfo()
  {
    if (request()->isPost()) {
      $rule = [
        'content|日程内容' => 'require',
        'start_date|开始日程日期' => 'require|date',
        'end_date|结束日程日期' => 'date',
        'cate|日程分类' => 'require',
      ];
      $data = [
        '_id' => input('param._id', '', 'trim'),
        'content' => input('param.content', '', 'trim'),
        'end_date' => input('param.end_date_str', '', 'trim'),
        'start_date' => input('param.start_date_str', '', 'trim'),
        'ps_id' => input('param.ps_id', '', 'trim'),
        'cate' => input('param.cate', '', 'trim'),
        'desc' => input('param.desc', '', 'trim'),
        'color' => input('param.color', '', 'trim'),
        'start_time' => input('param.start_time', '', 'trim'),
        'end_time' => input('param.end_time', '', 'trim'),
        'loop_num' => input('param.loop_num', '', 'trim'),
        'loop_type' => input('param.loop_type', '', 'trim'),
        'date_type' => input('param.date_type', '', 'trim'),
        'is_loop' => input('param.is_loop', '', 'trim'),
        'notice_open' => input('param.notice_open', '', 'trim'),
        'before_num' => input('param.before_num', '', 'trim'),
        'importance' => input('param.importance', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result = $validate->check($data);
      if (!$result) {
        return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
      }
      $data['is_loop'] = intval($data['is_loop']);
      $data['notice_open'] = intval($data['notice_open']);
      $addResult = doScheduleSave($data,$this->uid);
      if ($addResult['code'] == 200) {
        return json(['code' => 200, 'data' => '', 'msg' => '提交成功']);
      } else {
        return json(['code' => -1, 'data' => '', 'msg' => $addResult['msg']]);
      }
    } else {
      $id = input('param.id', '', 'trim');
      if (!$id) {
        return json(['code' => 200, 'data' => [], 'msg' => 'success']);
      }
      $data = Db::connect('mongodb')->name('schedule_list')->where('_id', $id)->find();
      $data['operate_time'] = (isset($data['operate_time']))?date('Y-m-d H:i:s', $data['operate_time']):'无';
      return json(['code' => 200, 'data' => $data, 'msg' => 'success']);
    }
  }
  public function delCate()
  {
    $rule = [
      'id|分类ID' => 'require',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $hasDoc = Db::connect('mongodb')->name('schedule_cate')->where('_id', $data['id'])->find();
    if (empty($hasDoc)) {
      return Result::Error('分类不存在或已删除');
    }
    Db::connect('mongodb')->name('schedule_cate')->where('_id', $data['id'])->delete();
    return Result::Success('','操作成功');
  }
  public function delSchedule()
  {
    $rule = [
      'id|日程ID' => 'require',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $hasDoc = Db::connect('mongodb')->name('schedule_list')->where('_id', $data['id'])->find();
    if (empty($hasDoc)) {
      return Result::Error('日程不存在或已删除');
    }
    Db::connect('mongodb')->name('schedule_list')->where('_id', $data['id'])->delete();
    Db::connect('mongodb')->name('schedule_list_log_' . $this->uid)->where('schedule_id', $data['id'])->delete();
    return Result::Success('','操作成功');
  }
  public function changeDefaultCate()
  {
    $rule = [
      'id|分类ID' => 'require',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $hasDoc = Db::connect('mongodb')->name('schedule_cate')->where('_id', $data['id'])->find();
    if (empty($hasDoc)) {
      return Result::Error('分类不存在或已删除');
    }
    $is_default = 0;
    $hasDoc['is_default'] = !isset($hasDoc['is_default'])?0: $hasDoc['is_default'];
    if ($hasDoc['is_default'] == 0) {
      $is_default = 1;
        Db::connect('mongodb')->name('schedule_cate')->update(['is_default' => 0]);
    }
    Db::connect('mongodb')->name('schedule_cate')->where('_id', $data['id'])->update(['is_default' => $is_default]);
    return Result::Success('','操作成功');
  }
  public function statusSchedule()
  {
    $rule = [
      'id|日程ID' => 'require',
      'status|日程状态' => 'require',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
      'status' => input('param.status', '', 'trim'),
      'beizhu' => input('param.beizhu', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $hasDoc = Db::connect('mongodb')->name('schedule_list')->where('_id', $data['id'])->find();
    if (empty($hasDoc)) {
      return Result::Error('日程不存在或已删除');
    }
    $update['is_finish'] = intval($data['status']);
    if ($hasDoc['is_loop'] == 1) {
      $update['is_finish'] = 0;
    }
    $update['operate_time'] = time();
    $update['beizhu'] = $data['beizhu'];
    Db::connect('mongodb')->name('schedule_list')->where('_id', $data['id'])->update($update);
    $scheduleLog['_id'] = createId();
    $scheduleLog['schedule_id'] = $data['id'];
    $scheduleLog['status'] = intval($data['status']);
    $scheduleLog['beizhu'] = $data['beizhu'];
    $scheduleLog['time'] = time();
    Db::connect('mongodb')->name('schedule_list_log')->insert($scheduleLog);
    $saveResult = [];
    if ($data['status'] == 1 && $hasDoc['is_loop'] == 1) {
      $hasDoc['is_force'] = 1;
      unset($hasDoc['developer_username'], $hasDoc['developer_id'],$hasDoc['end_event_time'],$hasDoc['start_event_time'],$hasDoc['before_event_time'],$hasDoc['create_time']);
      $saveResult = doScheduleSave($hasDoc, $this->uid);
    }
    return Result::Success(['status'=>$data['status'],'is_loop'=> $hasDoc['is_loop'], 'saveResult'=> $saveResult],'操作成功');
  }
  public function cate_list()
  {
    $rule = [
      'pageNo' => 'number',
      'pageSize' => 'number',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    // 构建查询条件
    
    if (!empty($data['title'])) {
      $where['title'] = ['like', $data['title']];
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    $dataList = Db::connect('mongodb')->name('schedule_cate')->where($where)->order('create_time', 'desc')->limit($limit, $data['pageSize'])->select()->toArray();
    $totalcount = Db::connect('mongodb')->name('schedule_cate')->where($where)->count('_id');
    foreach ($dataList as &$vo) {
      $vo['create_time'] = (isset($vo['create_time'])) ? date('Y-m-d H:i:s', $vo['create_time']) : '';
      $vo['is_default'] = (isset($vo['is_default'])) ? intval($vo['is_default']) : 0;
    }
    $returnData['data'] = $dataList;
    $returnData['totalCount'] = $totalcount;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  public function schedule_log_list()
  {
    $rule = [
      'id' => 'require',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    // 构建查询条件
    $dataList = Db::connect('mongodb')->name('schedule_list_log_' . $this->uid)->where('schedule_id', $data['id'])->order('time','desc')->select()->toArray();
    foreach ($dataList as &$vo) {
      $vo['time'] = (isset($vo['time'])) ? date('Y-m-d H:i:s', $vo['time']) : '';
    }
    return Result::Success($dataList);
  }
  public function list()
  {
    $rule = [
      'pageNo' => 'number',
      'pageSize' => 'number',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'cate' => input('param.cate', '', 'trim'),
      'date_range_format' => input('param.date_range_format', '', 'trim'),
      'status' => input('param.status', '', 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    // 构建查询条件
    $where = [];
    $where[] = ['developer_id','=',$this->uid];
    if (!empty($data['title'])) {
      $where[] = ['content', 'like', $data['title']];
    }
    if (!empty($data['cate'])) {
      $where[] = ['cate', '=', $data['cate']];
    }
    if (!empty($data['status'])) {
      if ($data['status'] == 'wc') {
        $where[] = ['is_finish', '=', 1];
      }else{
        $where[] = ['is_finish', '=', 0];
      }
    }
    $data['date_range_format'][0] = intval($data['date_range_format'][0]/1000);
    $data['date_range_format'][1] = intval($data['date_range_format'][1]/1000);
    if (($data['date_range_format'][1] - $data['date_range_format'][0]) == 86400) {
      $dataList = Db::connect('mongodb')->name('schedule_list')->where($where)->where('start_event_time', '<=', $data['date_range_format'][0])->where('end_event_time', '>=', $data['date_range_format'][1])->order('create_time', 'desc')->select()->toArray();
    }else{
      $dataList = Db::connect('mongodb')->name('schedule_list')->where($where)->whereOr('start_event_time', 'between', $data['date_range_format'])->whereOr('end_event_time', 'between', $data['date_range_format'])->order('create_time', 'desc')->select()->toArray();
    }
    $buildData = [];
    foreach ($dataList as &$vo) {
      $buildItem['id'] = $vo['_id'];
      $buildItem['color'] = (isset($vo['color']) && !empty($vo['color']))? $vo['color']:'';
      $time = (isset($vo['time']))?$vo['time'].' ':'';
      $importance = '';
      if (isset($vo['importance'])) {
        switch ($vo['importance']) {
          case 'zhong':
            $importance = '!! ';
            break;
          case 'gao':
            $importance = '!!! ';
            break;
        }
      }
      $buildItem['className'] = (isset($vo['is_finish']) && $vo['is_finish'] == 1)?' finish_event ': '';
      $buildItem['title'] = $importance.$time.$vo['content'];
      $buildItem['start'] = (isset($vo['start_event_time'])) ? date('Y-m-d', $vo['start_event_time']) : '';
      $buildItem['end'] = (isset($vo['end_event_time'])) ? date('Y-m-d', $vo['end_event_time']+86400) : '';
      $buildData[] = $buildItem;
    }
    return Result::Success($buildData);
  }
  public function onlyCateList()
  {
    $rule = [
      'pageNo'  => 'number',
      'pageSize'  => 'number',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'pageSize' => input('param.pageSize', 20, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    // 构建查询条件
    
    if (!empty($data['title'])) {
      $where['title'] = ['like', $data['title']];
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    $dataList = Db::connect('mongodb')->name('schedule_cate')->field('_id,title,desc,is_default')->where($where)->order('create_time', 'asc')->limit($limit, $data['pageSize'])->select()->toArray();
    foreach ($dataList as &$vo) {
      $vo['is_default'] = isset($vo['is_default'])? $vo['is_default']:0;
      $default = $vo['is_default'] == 1 ?'(默)':'';
      $vo['label'] = $vo['title']. $default;
      $vo['value'] = $vo['_id'];
    }
    return Result::Success($dataList);
  }
}
